package org.duang.db.sql;

import java.util.Map;

import javax.sql.DataSource;

import org.duang.config.Config;
import org.duang.db.Connection;
import org.duang.db.sql.ds.IDataSourceFactory;
import org.duang.kit.ObjectKit;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SqlConnection extends Connection {

	private static Logger logger = LoggerFactory.getLogger(SqlConnection.class);
	protected static DataSource ds = null;
	
	@Override
	protected void initDasebase() {
	}

	@Override
	protected void initAuth() {
	}

	public static void connect(Map<String, String> optionMap) throws Exception {
		initConnect(optionMap); // 初始化连接参数
	}
	
	private static void initConnect(Map<String, String> optionMap) throws Exception{
		if(ToolsKit.isEmpty(optionMap)){
			throw new NullPointerException("connection sql option map is null!");
		}
		if(ToolsKit.isEmpty(optionMap.get(Connection.URL_FIELD))  || 
				ToolsKit.isEmpty(optionMap.get(Connection.USERNAME_FIELD)) ||
				ToolsKit.isEmpty(optionMap.get(Connection.PASSWORD_FIELD))  ){
			throw new NullPointerException("connection sql fail:  "+  Connection.URL_FIELD +" or "
					+ Connection.USERNAME_FIELD + " or " + Connection.PASSWORD_FIELD + " is null!");
		}
		IDataSourceFactory dsFactory = null;
		if(ToolsKit.isEmpty(Config.getSqlDataSource())){
			dsFactory = ObjectKit.newInstance("org.duang.db.sql.ds.DuangDataSourceFactory");
		} else {
			dsFactory = ObjectKit.newInstance(Config.getSqlDataSource());
		}
		ds = dsFactory.getDataSource(optionMap);
		logger.info("connection " +  Connection.URL_FIELD + " success!");
	}
	
	public DataSource getDs() {
		return ds;
	}
	
	public void stop() {
		if(null != ds) ds = null;
	}
	
}
